//---------------------------------------------------------------------------
#include <windows.h>
#include "iostrm.h"
#include "memmap.h"

MemBlock::MemBlock(char *p, int size)
{
  set_ptr(p,size);
}

void MemBlock::set_ptr(char *p, int size)
{
  m_ptr = p;
  m_size = size;
  m_P = m_ptr;
}

char *MemBlock::text()
{
   if (m_ptr) m_ptr[m_size] = '\0';
   return m_ptr;
}


// ----------------------------- MemMapFile -----------------------------------

MemMapFile::MemMapFile(char *fname, int size,bool do_create)
 : MemBlock(NULL,size)
{
 m_hFile = INVALID_HANDLE_VALUE;
 m_hFileMap = NULL;
 m_size_override = size;
 m_do_create = do_create;
 if (fname != NULL) open(fname);
}

MemMapFile::~MemMapFile()
{
 close();
}

bool MemMapFile::open(char *fname, char *mname, void *base)
{
 long size;

 close(); // just in case

 if (fname) {
   m_hFile = CreateFile(fname, GENERIC_WRITE | GENERIC_READ,
	   0,NULL, m_do_create ? CREATE_ALWAYS :OPEN_EXISTING,
	   FILE_ATTRIBUTE_NORMAL,NULL);
   if (m_hFile == INVALID_HANDLE_VALUE) return false;
   size = GetFileSize(m_hFile,NULL);
 } else m_hFile = INVALID_HANDLE_VALUE;

 if (m_size_override) size = m_size_override;

 m_hFileMap = CreateFileMapping(m_hFile, NULL, PAGE_READWRITE,
                0, size, mname);

 if (m_hFileMap == NULL) return false;

 char *P = (char *)MapViewOfFileEx(m_hFileMap,FILE_MAP_WRITE, 0,0,0,base);

 if (P == NULL) return false;

 set_ptr(P, size);

 return true;
}

void MemMapFile::close()
{
  if (begin()) UnmapViewOfFile(begin());
  if (m_hFileMap) CloseHandle(m_hFileMap);
  if (m_hFile != INVALID_HANDLE_VALUE) CloseHandle(m_hFile);
}

ShareMemMap::ShareMemMap(char *mname, int size, void *base)
{
  m_size_override = size;
  open (NULL,mname,base);
}



